package com.jwsoft.manager.core.integration.common.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.system.SystemUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.enums.AccountType;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.bifang.module.base.core.utils.ServiceRequestUtil;
import com.bifang.module.system.common.enums.UserTypeEnum;
import com.bifang.module.system.core.dao.model.SysLoginOnline;
import com.bifang.module.system.core.dao.model.SysUser;
import com.bifang.module.system.core.dao.model.SysUserOther;
import com.bifang.module.system.core.dao.service.SysLoginOnlineService;
import com.bifang.module.system.core.dao.service.SysUserOtherService;
import com.bifang.module.system.core.dao.service.SysUserService;
import com.jwsoft.manager.common.constant.EduCache;
import com.jwsoft.manager.core.integration.common.JhIrsIntegration;
import com.jwsoft.manager.core.util.jhfc.RsaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.*;

/**
 * 金华大数据共享接口
 */
@Service
@Slf4j
public class JhIrsIntegrationImpl implements JhIrsIntegration {
    private final static String areaCode="330700";
    @Autowired
    CommonIntegration commonIntegration;
    @Autowired
    RedisHelper redisHelper;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserOtherService sysUserOtherService;
    @Autowired
    private SysLoginOnlineService sysLoginOnlineService;
    private final static String TOKEN="Epoint_WebSerivce_**##0601";
    private final static String searchdeptname="金华教育局";
    private final static String searchusername="经办人员";
    @Value("${system.config.zlb.appId}")
    private String zlbAppId;

    @Override
    public String refreshTokenByKeyJh(String appKey, String appsecret) {
        String refreshKey = "";
        String requestKey="";
        if(StringUtils.isBlank(appKey)){
            CommonVO commonVO = new CommonVO();
            commonVO.setParamKey("jhgx_client_id");
            commonVO.setAreaCode(areaCode);
            appKey = commonIntegration.getValueByKeyAndArea(commonVO);
            if (StringUtils.isBlank(appKey)) {
                throw new AppException("请先在系统参数表中设置jhgx_client_id");
            }
        }
        if(StringUtils.isBlank(appsecret)) {
            CommonVO commonVO1 = new CommonVO();
            commonVO1.setParamKey("jhgx_client_secret");
            commonVO1.setAreaCode(areaCode);
            appsecret = commonIntegration.getValueByKeyAndArea(commonVO1);
            if (StringUtils.isBlank(appsecret)) {
                throw new AppException("请先在系统参数表中设置jhgx_client_secret");
            }
        }

        CommonVO commonVO2 = new CommonVO();
        commonVO2.setParamKey("JHGX0001");
        commonVO2.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO2);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置JhGX0001（获取秘钥接口地址）");
        }
        Long requestTime= DateUtil.current();
        String sign= SecureUtil.md5(appKey+appsecret+requestTime).toLowerCase();
        Map<String, Object> map = new HashMap<>();
        map.put("appKey", appKey);
        map.put("sign",sign);
        map.put("requestTime",requestTime+"");
        String body = HttpUtil.get(url, map, 5000);
        log.info(body);
        if (StringUtils.isBlank(body)) {
            throw new AppException("获取金华共享请求秘钥失败，未返回信息");
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取金华共享请求秘钥失败：" + body);
        }
        if (jsonObject.get("code").equals("00")) {
            JSONObject data = jsonObject.getJSONObject("datas");
            refreshKey=data.getString("refreshSecret") + "";
            String refreshSecretEndTime=data.getString("refreshSecretEndTime") + "";
            Long refreshSecretEndTimeL=null;
            try {
                Date date = DateUtil.parseDate(refreshSecretEndTime);
                refreshSecretEndTimeL=date.getTime();
            }catch (Exception e){
                refreshSecretEndTimeL=Long.parseLong(refreshSecretEndTime);
            }
            //保存刷新秘钥到redis
            long refreshTimeInterval=((refreshSecretEndTimeL-System.currentTimeMillis())/1000-1800);
            redisHelper.set(EduCache.jh_irs_refresh_key,refreshKey,refreshTimeInterval);
            //更新请求秘钥到redis
            requestKey=data.getString("requestSecret") + "";
            String requestSecretEndTime=data.getString("requestSecretEndTime") + "";
            Long requestSecretEndTimeL=null;
            try {
                Date date = DateUtil.parseDate(requestSecretEndTime);
                requestSecretEndTimeL=date.getTime();
            }catch (Exception e){
                requestSecretEndTimeL=Long.parseLong(refreshSecretEndTime);
            }
            //保存刷新秘钥到redis
            long requestTimeInterval=(requestSecretEndTimeL-System.currentTimeMillis())/1000;
            redisHelper.set(EduCache.jh_irs_request_key,requestKey,600);
        }
        return requestKey;
    }

    @Override
    public String refreshTokenBySecJh(String appKey, String appsecret, String refreshKey) {
        String requestKey="";
        if(StringUtils.isBlank(appKey)) {
            CommonVO commonVO = new CommonVO();
            commonVO.setParamKey("jhgx_client_id");
            commonVO.setAreaCode(areaCode);
            appKey = commonIntegration.getValueByKeyAndArea(commonVO);
            if (StringUtils.isBlank(appKey)) {
                throw new AppException("请先在系统参数表中设置jhgx_client_id");
            }
        }
        if(StringUtils.isBlank(appsecret)) {
            CommonVO commonVO1 = new CommonVO();
            commonVO1.setParamKey("jhgx_client_secret");
            commonVO1.setAreaCode(areaCode);
            appsecret = commonIntegration.getValueByKeyAndArea(commonVO1);
            if (StringUtils.isBlank(appsecret)) {
                throw new AppException("请先在系统参数表中设置jhgx_client_secret");
            }
        }
        CommonVO commonVO2 = new CommonVO();
        commonVO2.setParamKey("JHGX0002");
        commonVO2.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO2);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置JHGX0002（刷新秘钥接口地址）");
        }
        Long requestTime=DateUtil.current();
        String sign= SecureUtil.md5(appKey+refreshKey+requestTime).toLowerCase();
        Map<String, Object> map = new HashMap<>();
        map.put("appKey", appKey);
        map.put("sign",sign);
        map.put("requestTime",requestTime+"");
        String body = HttpUtil.get(url, map, 5000);
        log.info(body);
        if (StringUtils.isBlank(body)) {
            throw new AppException("刷新金华共享请求秘钥失败，未返回信息");
        }
        JSONObject requestSecretJson = null;
        try {
            requestSecretJson = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("刷新金华共享请求秘钥失败：" + body);
        }
        String code = requestSecretJson.get("code").toString();
        if (code.equals("00")) {
            JSONObject data = requestSecretJson.getJSONObject("datas");
            requestKey=data.getString("requestSecret") + "";
            String requestSecretEndTime=data.getString("requestSecretEndTime") + "";
            Long requestSecretEndTimeL=null;
            try {
                Date date = DateUtil.parseDate(requestSecretEndTime);
                requestSecretEndTimeL=date.getTime();
            }catch (Exception e){
                requestSecretEndTimeL=Long.parseLong(requestSecretEndTime);
            }
            //保存刷新秘钥到redis
            long requestTimeInterval=(requestSecretEndTimeL-System.currentTimeMillis())/1000;
            redisHelper.set(EduCache.jh_irs_request_key,requestKey,600);
            //更新请求秘钥到redis
            refreshKey=data.getString("refreshSecret") + "";
            String refreshSecretEndTime=data.getString("refreshSecretEndTime") + "";
            Long refreshSecretEndTimeL=null;
            try {
                Date date = DateUtil.parseDate(refreshSecretEndTime);
                refreshSecretEndTimeL=date.getTime();
            }catch (Exception e){
                refreshSecretEndTimeL=Long.parseLong(refreshSecretEndTime);
            }
            long refreshTimeInterval=((refreshSecretEndTimeL-System.currentTimeMillis())/1000-1800);
            if(refreshTimeInterval>0){
                redisHelper.set(EduCache.jh_irs_refresh_key,refreshKey,refreshTimeInterval);
            }else{
                redisHelper.del(EduCache.jh_irs_refresh_key);
            }
        }else if(code.equals("03")){
            return refreshTokenByKeyJh(appKey,appsecret);
        }
        return requestKey;
    }

    @Override
    public Map<String, Object> setJhParams(Map<String, Object> paramsMap) {
        if (paramsMap==null){
            paramsMap =new HashMap<>();
        }
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("jhgx_client_id");
        commonVO.setAreaCode(areaCode);
        String appKey = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(appKey)) {
            throw new AppException("请先在系统参数表中设置jhgx_client_id");
        }
        CommonVO commonVO1 = new CommonVO();
        commonVO1.setParamKey("jhgx_client_secret");
        commonVO1.setAreaCode(areaCode);
        String appsecret = commonIntegration.getValueByKeyAndArea(commonVO1);
        if (StringUtils.isBlank(appsecret)) {
            throw new AppException("请先在系统参数表中设置jhgx_client_secret");
        }
        String requestKey="";
        if (redisHelper.hasKey(EduCache.jh_irs_request_key)){
            requestKey = (String) redisHelper.get(EduCache.jh_irs_request_key);
        }
        String refreshKey="";
        //请求秘钥过期，重新获取请求秘钥
        if(StringUtils.isBlank(requestKey)) {
            if (redisHelper.hasKey(EduCache.jh_irs_refresh_key)){
                refreshKey = (String) redisHelper.get(EduCache.jh_irs_refresh_key);
            }
            if (StringUtils.isBlank(refreshKey)) {
                requestKey = refreshTokenByKeyJh(appKey, appsecret);
            } else {
                //刷新秘钥未过期，根据刷新秘钥获取请求秘钥（获取请求秘钥也会返回刷新秘钥）
                requestKey = refreshTokenBySecJh(appKey,appsecret, refreshKey);
            }
        }
        if (StringUtils.isBlank(requestKey)){
            throw new AppException("未获取到市共享平台请求key");
        }
        String requestApiTime=System.currentTimeMillis()+"";
        String requestApiSign=SecureUtil.md5(appKey+requestKey+requestApiTime).toLowerCase();
        paramsMap.put("appKey",appKey);
        paramsMap.put("requestTime",requestApiTime);
        paramsMap.put("sign",requestApiSign);
        return paramsMap;
    }

    @Override
    public String refreshTokenByKeyIrs(String appKey,String appsecret) {
        String refreshKey = "";
        String requestKey="";
        if(StringUtils.isBlank(appKey)){
            CommonVO commonVO = new CommonVO();
            commonVO.setParamKey("ak_irs");
            commonVO.setAreaCode(areaCode);
            appKey = commonIntegration.getValueByKeyAndArea(commonVO);
            if (StringUtils.isBlank(appKey)) {
                throw new AppException("请先在系统参数表中设置ak_irs");
            }
        }
        if(StringUtils.isBlank(appsecret)) {
            CommonVO commonVO1 = new CommonVO();
            commonVO1.setParamKey("sk_irs");
            commonVO1.setAreaCode(areaCode);
            appsecret = commonIntegration.getValueByKeyAndArea(commonVO1);
            if (StringUtils.isBlank(appsecret)) {
                throw new AppException("请先在系统参数表中设置sk_irs");
            }
        }

        CommonVO commonVO2 = new CommonVO();
        commonVO2.setParamKey("IRSGX0001");
        commonVO2.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO2);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置IRSGX0001（获取秘钥接口地址）");
        }
        Long requestTime= DateUtil.current();
        String sign= SecureUtil.md5(appKey+appsecret+requestTime).toLowerCase();
        Map<String, Object> map = new HashMap<>();
        map.put("appKey", appKey);
        map.put("sign",sign);
        map.put("requestTime",requestTime+"");
        String body = HttpUtil.get(url, map, 5000);

        if (StringUtils.isBlank(body)) {
            throw new AppException("获取IRS请求秘钥失败，未返回信息");
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取IRS请求秘钥失败：" + body);
        }
        if (jsonObject.get("code").equals("00")) {
            JSONObject data = jsonObject.getJSONObject("datas");
            refreshKey=data.getString("refreshSecret") + "";
            String refreshSecretEndTime=data.getString("refreshSecretEndTime") + "";
            Long refreshSecretEndTimeL=Long.parseLong(refreshSecretEndTime);
            //保存刷新秘钥到redis
            long refreshTimeInterval=((refreshSecretEndTimeL-System.currentTimeMillis())/1000-1800);
            redisHelper.set(EduCache.irs_refresh_key,refreshKey,refreshTimeInterval);
            //更新请求秘钥到redis
            requestKey=data.getString("requestSecret") + "";
            String requestSecretEndTime=data.getString("requestSecretEndTime") + "";
            Long requestSecretEndTimeL=Long.parseLong(requestSecretEndTime);
            //保存刷新秘钥到redis
            long requestTimeInterval=(requestSecretEndTimeL-System.currentTimeMillis())/1000;
            redisHelper.set(EduCache.irs_request_key,requestKey,600);
        }
        return requestKey;
    }

    @Override
    public String refreshTokenBySecIrs(String appKey,String appsecret,String refreshKey) {
        String requestKey="";
        if(StringUtils.isBlank(appKey)) {
            CommonVO commonVO = new CommonVO();
            commonVO.setParamKey("ak_irs");
            commonVO.setAreaCode(areaCode);
            appKey = commonIntegration.getValueByKeyAndArea(commonVO);
            if (StringUtils.isBlank(appKey)) {
                throw new AppException("请先在系统参数表中设置ak_irs");
            }
        }
        if(StringUtils.isBlank(appsecret)) {
            CommonVO commonVO1 = new CommonVO();
            commonVO1.setParamKey("sk_irs");
            commonVO1.setAreaCode(areaCode);
            appsecret = commonIntegration.getValueByKeyAndArea(commonVO1);
            if (StringUtils.isBlank(appsecret)) {
                throw new AppException("请先在系统参数表中设置sk_irs");
            }
        }
        CommonVO commonVO2 = new CommonVO();
        commonVO2.setParamKey("IRSGX0002");
        commonVO2.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO2);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置IRSGX0002（刷新秘钥接口地址）");
        }
        Long requestTime=DateUtil.current();
        String sign= SecureUtil.md5(appKey+refreshKey+requestTime).toLowerCase();
        Map<String, Object> map = new HashMap<>();
        map.put("appKey", appKey);
        map.put("sign",sign);
        map.put("requestTime",requestTime+"");
        String body = HttpUtil.get(url, map, 5000);

        if (StringUtils.isBlank(body)) {
            throw new AppException("刷新IRS请求秘钥失败，未返回信息");
        }
        JSONObject requestSecretJson = null;
        try {
            requestSecretJson = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("刷新IRS请求秘钥失败：" + body);
        }
        String code = requestSecretJson.get("code").toString();
        if (code.equals("00")) {
            JSONObject data = requestSecretJson.getJSONObject("datas");
            requestKey=data.getString("requestSecret") + "";
            String requestSecretEndTime=data.getString("requestSecretEndTime") + "";
            Long requestSecretEndTimeL=Long.parseLong(requestSecretEndTime);
            //保存刷新秘钥到redis
            long requestTimeInterval=(requestSecretEndTimeL-System.currentTimeMillis())/1000;
            redisHelper.set(EduCache.irs_request_key,requestKey,600);
            //更新请求秘钥到redis
            refreshKey=data.getString("refreshSecret") + "";
            String refreshSecretEndTime=data.getString("refreshSecretEndTime") + "";
            Long refreshSecretEndTimeL=Long.parseLong(refreshSecretEndTime);
            long refreshTimeInterval=((refreshSecretEndTimeL-System.currentTimeMillis())/1000-1800);
            if(refreshTimeInterval>0){
                redisHelper.set(EduCache.irs_refresh_key,refreshKey,refreshTimeInterval);
            }else{
                redisHelper.del(EduCache.irs_refresh_key);
            }
        }else if(code.equals("03")){
            return refreshTokenByKeyIrs(appKey,appsecret);
        }
        return requestKey;
    }

    @Override
    public Map<String, Object> setIrsParams(Map<String, Object> paramsMap) {
        if (paramsMap==null){
            paramsMap =new HashMap<>();
        }
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("ak_irs");
        commonVO.setAreaCode(areaCode);
        String appKey = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(appKey)) {
            throw new AppException("请先在系统参数表中设置ak_irs");
        }
        CommonVO commonVO1 = new CommonVO();
        commonVO1.setParamKey("sk_irs");
        commonVO1.setAreaCode(areaCode);
        String appsecret = commonIntegration.getValueByKeyAndArea(commonVO1);
        if (StringUtils.isBlank(appsecret)) {
            throw new AppException("请先在系统参数表中设置sk_irs");
        }
        String requestKey="";
        if (redisHelper.hasKey(EduCache.irs_request_key)){
            requestKey = (String) redisHelper.get(EduCache.irs_request_key);
        }
        String refreshKey="";
        //请求秘钥过期，重新获取请求秘钥
        if(StringUtils.isBlank(requestKey)) {
            if (redisHelper.hasKey(EduCache.irs_refresh_key)){
                refreshKey = (String) redisHelper.get(EduCache.irs_refresh_key);
            }
            if (StringUtils.isBlank(refreshKey)) {
                requestKey = refreshTokenByKeyIrs(appKey, appsecret);
            } else {
                //刷新秘钥未过期，根据刷新秘钥获取请求秘钥（获取请求秘钥也会返回刷新秘钥）
                requestKey = refreshTokenBySecIrs(appKey,appsecret, refreshKey);
            }
        }
        if (StringUtils.isBlank(requestKey)){
            throw new AppException("未获取到市共享平台请求key");
        }
        String requestApiTime=System.currentTimeMillis()+"";
        String requestApiSign=SecureUtil.md5(appKey+requestKey+requestApiTime).toLowerCase();
        paramsMap.put("appKey",appKey);
        paramsMap.put("requestTime",requestApiTime);
        paramsMap.put("sign",requestApiSign);
        Map<String,Object> additional=new HashMap<>();
        additional.put("powerMatters","许可-0000-00");
        additional.put("subPowerMatters","许可-0000-0101");
        additional.put("accesscardId","jhjy");
        paramsMap.put("additional",JSON.toJSONString(additional));
        return paramsMap;
    }

    @Override
    public Map<String, String> setHeaders(String userId,String idcard,String ip,Map<String, Object> paramsMap) {

        Map<String, String>  headers=new HashMap<>();
        if (!CollectionUtils.isEmpty(paramsMap)){
            if (paramsMap.get("appKey")!=null) {
                headers.put("appKey", paramsMap.get("appKey").toString());
            }
            if (paramsMap.get("requestTime")!=null) {
                headers.put("requestTime", paramsMap.get("requestTime").toString());
            }
            if (paramsMap.get("sign")!=null) {
                headers.put("sign", paramsMap.get("sign").toString());
            }
        }
        List<String> userIds=new ArrayList<>();
        if (StringUtils.isBlank(userId)&&StringUtils.isNotBlank(idcard)) {
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().select(SysUser::getUserId).eq(StringUtils.isNotBlank(userId), SysUser::getUserId, userId)
                    .eq(StringUtils.isNotBlank(idcard), SysUser::getUserType, UserTypeEnum.USER.getType())
                    .eq(StringUtils.isNotBlank(idcard), SysUser::getIdcard, CommonSecureUtil.aesEncrypt(idcard));
            List<SysUser> sysUsers=sysUserService.list(queryWrapper);
            if (!CollectionUtils.isEmpty(sysUsers)){
                for (SysUser sysUser:sysUsers){
                    userIds.add(sysUser.getUserId());
                }
            }
        }
        if (StringUtils.isNotBlank(userId)){
            userIds.add(userId);
        }
        if (StringUtils.isNotBlank(userId)&&StringUtils.isBlank(ip)){
            //ip为空，获取登录记录里面的ip
            //只查询最新一条数据
            QueryWrapper<SysLoginOnline> loginOnlineQueryWrapper=new QueryWrapper<>();
            loginOnlineQueryWrapper.lambda().select(SysLoginOnline::getLoginId).eq(SysLoginOnline::getUserId,userId).orderByDesc(SysLoginOnline::getLoginTime)
                    .last("limit 1");
            List<SysLoginOnline> sysLoginOnlines=sysLoginOnlineService.list(loginOnlineQueryWrapper);
            if (!CollectionUtils.isEmpty(sysLoginOnlines)){
                ip=sysLoginOnlines.get(0).getLoginIp();
            }
        }
        if (StringUtils.isBlank(ip)){
            try {
                ip= ServiceRequestUtil.getLocalIP();
            } catch (UnknownHostException e) {
                log.error("获取ip失败",e);
            } catch (SocketException e) {
                log.error("获取ip失败",e);
            }
        }
        if (!CollectionUtils.isEmpty(userIds)) {
            QueryWrapper<SysUserOther> otherQueryWrapper = new QueryWrapper<>();
            otherQueryWrapper.lambda().select(SysUserOther::getUserId, SysUserOther::getOpenId)
                    .in(SysUserOther::getUserId, userIds).isNotNull(SysUserOther::getOpenId)
                    .eq(SysUserOther::getLoginType, AccountType.ZLB.getKey()).orderByDesc(SysUserOther::getSysId);
            List<SysUserOther> userOthers = sysUserOtherService.list(otherQueryWrapper);
            headers.put("X-SECURITY-CHECK-TYPE", "ZLB");
            if (!CollectionUtils.isEmpty(userOthers)) {
                headers.put("X-SECURITY-USER-ID", userOthers.get(0).getOpenId());
                headers.put("X-SECURITY-CHECK-TYPE", "ZLB");
            } else {
                CommonVO commonVO = new CommonVO();
                commonVO.setParamKey("zdd_userId");
                commonVO.setAreaCode(areaCode);
                String zddUserIdStr = commonIntegration.getValueByKeyAndArea(commonVO);
                List<String> zddidList = new ArrayList<>();
                if (StringUtils.isNotBlank(zddUserIdStr)) {
                    zddidList = Arrays.asList(zddUserIdStr.split(","));
                }
                if (!CollectionUtils.isEmpty(zddidList)) {
                    //随机取zddid
                    int index = (int) (Math.random() * zddidList.size());
                    headers.put("X-SECURITY-USER-ID", zddidList.get(index));
                    headers.put("X-SECURITY-CHECK-TYPE", "ZZD");
                } else {
                    headers.put("X-SECURITY-USER-ID", zlbAppId);
                }

            }
        }else{
            CommonVO commonVO = new CommonVO();
            commonVO.setParamKey("zdd_userId");
            commonVO.setAreaCode(areaCode);
            String zddUserIdStr = commonIntegration.getValueByKeyAndArea(commonVO);
            List<String> zddidList=new ArrayList<>();
            if (StringUtils.isNotBlank(zddUserIdStr)) {
                zddidList= Arrays.asList(zddUserIdStr.split(","));
            }
            if (!CollectionUtils.isEmpty(zddidList)){
                //随机取zddid
                int index = (int) (Math.random() * zddidList.size());
                headers.put("X-SECURITY-USER-ID", zddidList.get(index));
                headers.put("X-SECURITY-CHECK-TYPE", "ZZD");
            }else{
                headers.put("X-SECURITY-USER-ID", zlbAppId);
            }

        }

        headers.put("X-SECURITY-UESR-IP",ip);
        headers.put("X-SECURITY-SERVICE-ID",zlbAppId);
        return headers;
    }

    /**
     * 省公安厅居民户口簿(家庭) irs
     *
     * @param czrkgmsfhm 身份证号码
     **/
    @Override
    public JSONArray getFamilyInfoIrs(String czrkgmsfhm,String ip) {

        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("IRSGX0003");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置IRSGX0003（省公安厅居民户口簿(家庭)Irs接口地址）");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("czrkgmsfhm", czrkgmsfhm);
        map.put("User_ID", czrkgmsfhm);
        map.put("Organization_Id", "330700");
        map.put("Organization", "金华市教育局");
        setIrsParams(map);
        Map<String, String> headers = setHeaders(null,czrkgmsfhm,ip,map);
        String body =HttpUtil.createGet(url).addHeaders(headers).form(map).timeout(6000).execute().body();
        if (StringUtils.isBlank(body)) {
            throw new AppException("获取省公安厅居民户口簿(家庭)信息失败，未返回信息");
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取省公安厅居民户口簿(家庭)信息失败：" + body);
        }
        String code = jsonObject.getString("code");
        if ("00".equals(code)) {
            JSONArray jsonArray = jsonObject.getJSONArray("datas");
            return jsonArray;
        } else {
            String msg = jsonObject.getString("msg");
            if (StringUtils.isBlank(msg)) {
                msg = jsonObject.getString("message");
            }
            throw new AppException("IRS平台接口返回：错误码：" + code + "错误描述：" + msg);
        }
    }

    @Override
    public JSONArray getJzzIrs(String sfzh, String xm,String ip) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("IRSGX0005");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置IRSGX0005（省公安厅居住证Irs接口地址）");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("sfzh", sfzh);
        map.put("xm", xm);
        map.put("User_ID", sfzh);
        map.put("User_Name", xm);
        map.put("Organization_Id", "330700");
        map.put("Organization", "金华市教育局");
        setIrsParams(map);
        Map<String, String> headers = setHeaders(null,sfzh,ip,map);
        String body =HttpUtil.createGet(url).addHeaders(headers).form(map).timeout(15000).execute().body();


        if (StringUtils.isBlank(body)) {
            throw new AppException("获取省公安厅居住证信息失败，未返回信息");
        }
        System.out.println(body);
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取省公安厅居住证信息失败：" + body);
        }
        String code = jsonObject.getString("code");
        if ("00".equals(code)) {
            JSONArray jsonArray = jsonObject.getJSONArray("datas");
            return jsonArray;
        } else {
            String msg = jsonObject.getString("msg");
            if (StringUtils.isBlank(msg)) {
                msg = jsonObject.getString("message");
            }
            throw new AppException("IRS平台接口返回：错误码：" + code + "错误描述：" + msg);
        }
    }
    /**
     *
     * 社会保险个人参保信息最新状态查询 省irs
     * **/
    @Override
    public JSONArray getCbIrs(String aac002,String ip) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("IRSGX0007");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置IRSGX0007（省社会保险个人参保信息最新状态查询Irs接口地址）");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("AAC002", aac002);
        setIrsParams(map);
        Map<String, String> headers = setHeaders(null,aac002,ip,map);
        String body =HttpUtil.createGet(url).addHeaders(headers).form(map).timeout(6000).execute().body();

        if (StringUtils.isBlank(body)) {
            throw new AppException("获取省社会保险个人参保信息最新状态查询信息失败，未返回信息");
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取省社会保险个人参保信息最新状态查询信息失败：" + body);
        }
        String code = jsonObject.getString("code");
        if ("00".equals(code)) {
            JSONArray jsonArray = jsonObject.getJSONArray("datas");
            return jsonArray;
        } else {
            String msg = jsonObject.getString("msg");
            if (StringUtils.isBlank(msg)) {
                msg = jsonObject.getString("message");
            }
            throw new AppException("IRS平台接口返回：错误码：" + code + "错误描述：" + msg);
        }
    }
    /**
     *
     * 社保历史参保缴费明细 省irs
     * **/
    @Override
    public JSONArray getCbJfIrs(String aac002, String aac003, String aae030, String aae031, String aae140,String aab301,String ip) {
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("IRSGX0008");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置IRSGX0008（省社保历史参保缴费明细查询Irs接口地址）");
        }
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> mapCx = new HashMap<>();
        mapCx.put("aab301", StringUtils.isBlank(aab301)?"330799|330702|330703|330704|":aab301+"|");
        mapCx.put("aac002", aac002);
        mapCx.put("aac003", aac003);
        mapCx.put("aae030", aae030);
        mapCx.put("aae031", aae031);
        mapCx.put("aae140", aae140);
        mapCx.put("bze601", "IZNDKSALD");
        mapCx.put("msgno", "4207");
        map.put("materialName", "个人缴费");
        map.put("User_ID", aac002);
        map.put("User_Name", aac003);
        map.put("Organization_Id", "330700");
        map.put("Organization", "金华市教育局");
        String jsonParam=JSON.toJSONString(mapCx);
        try {
            jsonParam = URLEncoder.encode(jsonParam, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        map.put("intext", jsonParam);
        map.put("interfaceCode", "I30701600003029/2861");
        setIrsParams(map);
        String charset="UTF-8";
        Map<String, String> headers = setHeaders(null,aac002,ip,map);
        headers.put("Content-Type", "application/x-www-form-urlencoded");

        HttpResponse response = HttpUtil.createPost(url).charset(charset).addHeaders(headers).form(map).timeout(6 * 1000).execute();
        String body = response.body();
        if (StringUtils.isBlank(body)) {
            throw new AppException("获取省社保历史参保缴费明细信息失败，未返回信息");
        }

        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取省社保历史参保缴费明细信息失败：" + body);
        }
        System.out.println("社保明细");
        System.out.println(JSON.toJSONString(map));
        System.out.println(body);
        String code = jsonObject.getString("code");
        if ("00".equals(code)) {
            JSONObject datas = jsonObject.getJSONObject("datas");
            JSONArray jsonArray =new JSONArray();
            if(datas.get("data")==null){
                jsonArray=datas.getJSONArray("datas");
            }else{
                jsonArray=datas.getJSONArray("data");
            }
            if(jsonArray==null){
                return new JSONArray();
            }
            return jsonArray;

        } else {
            String msg = jsonObject.getString("msg");
            if (StringUtils.isBlank(msg)) {
                msg = jsonObject.getString("message");
            }
            throw new AppException("IRS平台接口返回：错误码：" + code + "错误描述：" + msg);
        }
    }


    /**
     *
     * 金华市本级不动产权属信息查询（姓名+证件号） 金华Irs
     * **/
    @Override
    public JSONArray getFcJh(String xm, String zjh,String ip) {
        if (StringUtils.isBlank(zjh)){
            return new JSONArray();
        }
        if (zjh.length()!=18||!IdcardUtil.isValidCard(zjh)){
            return new JSONArray();
        }
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("JHGX0003");
        commonVO.setAreaCode(areaCode);
        String url = commonIntegration.getValueByKeyAndArea(commonVO);
        if (StringUtils.isBlank(url)) {
            throw new AppException("请先在系统参数表中设置JHGX0003（金华市本级不动产权属信息查询（姓名+证件号）Irs接口地址）");
        }
        Map<String, Object> encryptParam = new HashMap<>();
        List<Map<String,Object>> querymanList=new ArrayList<>();
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("name",xm);
        queryMap.put("zjh",zjh);
        querymanList.add(queryMap);
        List<String> zjhList = new ArrayList<>();
        zjhList.add(zjh);

        encryptParam.put("isShowXzxx","1");
        encryptParam.put("querymanList",querymanList);
        encryptParam.put("timestamp",DateUtil.current()+"");
        encryptParam.put("zjhList", zjhList);
        encryptParam.put("xzqbm","330701");
        encryptParam.put("cdbh", "cdbh"+System.currentTimeMillis());
        String params ="";
        try {
            String jsonParam = JSON.toJSONString(encryptParam);
            jsonParam = URLEncoder.encode(jsonParam, "UTF-8");
            params=RsaUtil.encryptByPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCBf1fx204rAt3PG7unKoDTvMaaJIGiKumqzliicL/xzixmQ5FGVBTfuMM0Zeh7fl/Si2y/FLoe+ayq/PbSwl5CmLFUf/dRNKhlwItcQs9p3RBwA9+GUITVoafjIDhFPh9Wm/+C+RBfHDoM9tJirAMox0+OKqltnZ6i3I/JQ12NJwIDAQAB", jsonParam);
        }catch (Exception e){
            throw new AppException("加密失败");
        }
        Map<String, Object> encryptEntity = new HashMap<>();
        encryptEntity.put("userId", "899aad0c-0439-4fca-8832-5a778c26b0d6");
        encryptEntity.put("encryptParam", params);
        encryptEntity.put("sign", "");
        Map<String, Object> map = new HashMap<>();
        map.put("encryptEntity", JSON.toJSONString(encryptEntity));
        setJhParams(map);
        System.out.println(JSON.toJSONString(map));
        Map<String, String> headers = setHeaders(null,zjh,ip,map);
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        String charset="UTF-8";
        HttpResponse response = HttpUtil.createPost(url).charset(charset).addHeaders(headers).form(map).timeout(6 * 1000).execute();
        String body = response.body();
        if (StringUtils.isBlank(body)) {
            throw new AppException("获取金华市本级不动产权属信息查询（姓名+证件号）信息失败，未返回信息");
        }
        System.out.println(body);
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
        } catch (Exception e) {
            throw new AppException("获取金华市本级不动产权属信息查询（姓名+证件号）信息失败：" + body);
        }
        String code = jsonObject.getString("code");
        if ("00".equals(code)) {
            JSONObject datas = jsonObject.getJSONObject("datas");
            String fcCode = datas.getString("code");
            if("0".equalsIgnoreCase(fcCode)){
                JSONObject fcObject = datas.getJSONObject("data");
                JSONArray jsonArray=fcObject.getJSONArray("list");
                return jsonArray;
            }else{
                throw new AppException("获取金华市本级不动产权属信息查询（姓名+证件号）信息失败：code("+fcCode+")" + datas.getString("msg"));
            }

        } else {
            String msg = jsonObject.getString("msg");
            if (StringUtils.isBlank(msg)) {
                msg = jsonObject.getString("message");
            }
            throw new AppException("IRS平台接口返回：错误码：" + code + "错误描述：" + msg);
        }

    }
}
